package com.ohos.magnetx;

import magnet.Instance;
import magnet.SelectorFilter;

@Instance(
        type = SelectorFilter.class,
        classifier = "openharmony"
)
public class OhosSelectorFilter extends SelectorFilter {
    private static final String VERSION_ERROR = "Make sure to use same versions of 'magnet' and 'magnetx' packages.";

    @Override
    public boolean filter(String[] selector) {
        if (selector.length < 4) {
            throw new IllegalStateException("Unexpected selector length: " + selector.length + ". $VERSION_ERROR");
        } else {
            if (!selector[1].equals("api")) {
                throw new IllegalStateException("Unexpected selector key " + selector[1] + ". $VERSION_ERROR");
            } else {
                Operator operator;
                switch (selector[2]) {
                    case ">=":
                        operator = GreatOrEqual.getInstance();
                        break;
                    case "<=":
                        operator = LessOrEqual.getInstance();
                        break;
                    case ">":
                        operator = Great.getInstance();
                        break;
                    case "<":
                        operator = Less.getInstance();
                        break;
                    case "==":
                        operator = Equal.getInstance();
                        break;
                    case "!=":
                        operator = NotEqual.getInstance();
                        break;
                    case "in":
                        operator = In.getInstance();
                        break;
                    case "!in":
                        operator = NotIn.getInstance();
                        break;
                    default:
                        throw new IllegalStateException("Unsupported operator " + selector[2] + ". $VERSION_ERROR");
                }
                if (operator != null) {
                    if (operator instanceof Operator.OneOperand) {
                        return ((Operator.OneOperand) operator).apply(Integer.parseInt(selector[3]));
                    } else {
                        if (selector.length > 4) {
                            return ((Operator.TwoOperands) operator).apply(Integer.parseInt(selector[3]), Integer.parseInt(selector[4]));
                        } else {
                            throw new IllegalStateException("Unexpected selector length " + selector.length + "for" + operator + ". Make sure to use same versions of 'magnet' and 'magnetx' packages.");
                        }
                    }
                } else {
                    throw new IllegalStateException("Unsupported operator type: $operator");
                }
            }
        }
    }
}
